package com.hwy.widget.utils;

import android.text.TextUtils;

import androidx.annotation.Nullable;

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/3/15 22:23
 * 说明: Json格式化显示工具类
 * =======================================
 */
public class JsonFormatUtil {

    /**
     * 格式化显示json
     */
    public static String format(@Nullable String json) {
        if (TextUtils.isEmpty(json)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        int level = 0;
        for (int index = 0; index < json.length(); index++) {
            char c = json.charAt(index);
            if (level > 0 && '\n' == sb.charAt(sb.length() - 1)) {
                sb.append(getIndentationLevel(level));
            }
            switch (c) {
                case '{':
                case '[':
                    sb.append(c + "\n");
                    level++;
                    break;
                case ',':
                    sb.append(c + "\n");
                    break;
                case '}':
                case ']':
                    sb.append("\n");
                    level--;
                    sb.append(getIndentationLevel(level));
                    sb.append(c);
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        return sb.toString();
    }

    private static String getIndentationLevel(int level) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < level; i++) {
            sb.append("\t");
        }
        return sb.toString();
    }

}
